<?php

namespace App\Admin\Grid\Displayers;

class SwitchDisplay extends AbstractDisplayer
{
    protected $states = [
        'on'  => ['value' => 1, 'text' => '开'],
        'off' => ['value' => 0, 'text' => '关'],
    ];

    protected function updateStates($states)
    {
        foreach (array_dot($states) as $key => $state) {
            array_set($this->states, $key, $state);
        }
    }

    public function display($states = [])
    {
        $this->updateStates($states);

        $name = $this->column->getName();

        $key = $this->row->{$this->grid->getKeyName()};

        $checked = $this->states['on']['value'] == $this->value ? 'checked' : '';

        $layText = $this->states['on']['text'] . '|' . $this->states['off']['text'];

        $values = json_encode([
            'on'  => $this->states['on']['value'],
            'off' => $this->states['off']['value'],
        ]);

        return <<<EOT
<input type="checkbox" lay-skin="switch" lay-text="$layText" lay-filter="grid-switch" $checked
       data-resource="/{$this->grid->resource()}/{$key}" data-name="$name"
       data-values='$values'
>
EOT;
    }
}
